﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SmallMediaLibrary;
using System.Threading;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace SmallVideoPlayer
{
    /// <summary>
    /// SimpleVideoSource demonstrates a quick way to improve the framerate in applications where the frame access is mutually exclusive (e.g. using GDI)
    /// The frames are swapped on each call to GetFrame, relying on VideoPlayers locks to update the active frame when a complete frame has been written
    /// to it, and returning the last one to be completed.
    /// To improve this, consider adding the frame swap routine in another thread
    /// </summary>
    public class SimpleVideoSource
    {
        public SimpleVideoSource(VideoPlayer player, int width, int height)
        {
            this.player = player;

            readingFrame = new VideoFrame(width, height);
            readingFrame.Buffer = GCHandle.Alloc(new byte[readingFrame.BufferLength], GCHandleType.Pinned).AddrOfPinnedObject();

            writingFrame = new VideoFrame(width, height);
            writingFrame.Buffer = GCHandle.Alloc(new byte[writingFrame.BufferLength], GCHandleType.Pinned).AddrOfPinnedObject();

        }

        VideoFrame readingFrame;
        VideoFrame writingFrame;

        VideoPlayer player;

        public VideoFrame GetFrame()
        {
            VideoFrame cframe = readingFrame;
            readingFrame = writingFrame;
            writingFrame = cframe;

            player.SetReceivingFrame(writingFrame);

            return readingFrame;
        }
    }
 
}
